'use strict';

var crypto = require('crypto');
var dt = require('sequelize');
/**
 * RDBMS User Model
 */
module.exports = function(panes)
{
	/**
	 * a setter to hash the password for password field
	 */
	var hashPassword = function(password)
	{
		if (password) {
			var salt = crypto.randomBytes(16).toString('base64');
			this.setDataValue('salt' , salt);
		    password = crypto.pbkdf2Sync(password, new Buffer(salt, 'base64'), 10000, 64).toString('base64');
		}
		this.setDataValue('password', password);
	};

	panes.model('User', {
		firstName: {
			type: dt.STRING,
			field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
		},
		lastName: {
			type: dt.STRING,
			field: 'last_name'
		},
		displayName: {
	        type: dt.STRING,
			field: 'display_name'
	    },
	    telephone: {
	        type: dt.INTEGER(11).UNSIGNED,
	        defaultValue: '00000000000',
	        validate: {
	        	is: ['/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/' , '']
	    	}
		},
	    email: {
	        type: dt.STRING,
	        defaultValue: '',
	        validate: {
				isEmail: true
			}
	    },
	    username: {
	        type: dt.STRING,
	        unique: true,
	        validate: {
				notNull: true,
				notEmpty: true
			}
	    },
	    password: {
	        type: dt.STRING,
	        defaultValue: '',
			set: hashPassword,
	        validate: {
				min: 6
			}
	    },
	    salt: {
	        type: dt.STRING
	    },
	    provider: {
	        type: dt.STRING,
	        validate: {
				notNull: true,
				notEmpty: true
			}
	    },
		// @TODO this require two additional database for linking unless its using postgresql
	    // providerData: {},
	    // additionalProvidersData: {},
	    roles: {
	        type: [{
	            type: dt.STRING,
	            enum: ['user', 'admin']
	        }],
	        defaultValue: ['user']
	    },
	    updated: {
	        type: dt.DATE
	    },
	    created: {
	        type: dt.DATE,
	        defaultValue: Sequelize.NOW
	    },
	    /* For reset password */
	    resetPasswordToken: {
	        type: dt.STRING
	    },
	    resetPasswordExpires: {
	        type: dt.DATE
	    }
	});

};
